/*
 * Copyright (c) 2022 Hunan OpenValley Digital Industry Development Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>
#include "cmsis_os2.h"
#include "ohos_run.h"
#include "osal_irq.h"

/* ADC2 Example*/
#include <stdio.h>
#include <stdlib.h>
#include "driver/gpio.h"
#include "driver/adc_common.h"
#include "esp_adc_cal.h"


//ADC所接的通道
#define ADC2_TEST_CHANNEL ADC2_CHANNEL_9

osThreadId_t g_taskID = NULL;
int read_raw;
int ret;
int count;

//ADC初始化
//ADC_ATTEN_DB_0:表示参考电压为1.1V
//ADC_ATTEN_DB_2_5:表示参考电压为1.5V
//ADC_ATTEN_DB_6:表示参考电压为2.2V
//ADC_ATTEN_DB_11:表示参考电压为3.9V
void adc_Init()
{
	//adc1_config_width(ADC_WIDTH_12Bit);// 12位分辨率
	adc2_config_channel_atten(ADC2_TEST_CHANNEL,ADC_ATTEN_DB_0);// 设置通道6和3.9V参考电压
}



static void adc_test(void)
{
    static uint8_t state = 0;
	adc_Init();
	while(1){
        switch(state)
        {
            case 0:
            {
                esp_err_t r = adc2_get_raw( ADC2_TEST_CHANNEL, ADC_WIDTH_12Bit, &read_raw);
                if ( r == ESP_OK ) {
                    ret += read_raw;
                    count ++;
                } else if ( r == ESP_ERR_TIMEOUT ) {            //说明ADC2的引脚已被用为WIFI占用
                    printf("ADC2 used by Wi-Fi.\n");
                    break;
                }
                if(count == 10)
                {
                    state = 1;
                }
            }
            case 1:
            {
                printf("MQ2 adc value is %d\r\n",ret/count);
                state = 0;
                ret = 0;
                count = 0;
            }
        }

            // esp_err_t r = adc2_get_raw( ADC2_TEST_CHANNEL, ADC_WIDTH_12Bit, &read_raw);
            // if ( r == ESP_OK ) {
            //     printf("%d\r\n",read_raw);
            // } else if ( r == ESP_ERR_TIMEOUT ) {            //说明ADC2的引脚已被用为WIFI占用
            //     printf("ADC2 used by Wi-Fi.\n");
            //     break;
            // }
       
		//ADC的结果转换成电压
		osDelay(100);
	}
}

static void adc_task(void)
{
    osThreadAttr_t attr;
    attr.name = "adc_test";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 1024;
    attr.priority = 26;
    g_taskID = osThreadNew((osThreadFunc_t)adc_test, NULL, &attr);
    if (g_taskID == NULL) {
        printf("Failed to create Test ADC thread!\n");
    }
}

OHOS_APP_RUN(adc_task);
